package com.example.nowcodercommunity.service;

import com.example.nowcodercommunity.dao.MessageMapper;
import com.example.nowcodercommunity.entity.Message;
import com.example.nowcodercommunity.util.SensitiveFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

@Service
public class MessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private SensitiveFilter filter;

    public List<Message> getConversationsByUserId(int userId,int offset,int limit){
        return messageMapper.selectConversations(userId,offset,limit);
    }

    public List<Message> getMessagesByConversation(String conversationId,int offset,int limit){
        return messageMapper.selectMessagesByConversation(conversationId, offset, limit);
    }

    public Message getNewestNotice(int userId, String topic){
        return messageMapper.selectNewestNotice(userId, topic);
    }

    public List<Message> getNotices(int userId, String topic, int offset, int limit){
        return messageMapper.selectNotices(userId, topic, offset, limit);
    }

    public int getCountOnConversation(int userId){
        try{
            return messageMapper.selectConversationCount(userId);
        }catch (Exception e){
            return 0;
        }
    }

    public int getCountOnLetter(String conversationId){
        try{
            return messageMapper.selectLetterCount(conversationId);
        }catch (Exception e){
            return 0;
        }
    }

    public int getCountOnUnreadLetter(int userId,String conversationId){
        try{
            return messageMapper.selectLetterUnreadCount(userId, conversationId);
        }catch (Exception e){
            return 0;
        }
    }

    public int getNoticeCount(int userId, String topic){
        return messageMapper.selectNoticeCount(userId, topic);
    }

    public int getUnreadNoticeCount(int userId, String topic){
        return messageMapper.selectUnreadNoticeCount(userId, topic);
    }

    public int addMessage(Message message){
        String content = message.getContent();
        content = filter.filter(content);
        content = HtmlUtils.htmlEscape(content);

        message.setContent(content);
        return messageMapper.insertMessage(message);
    }

    public int addNotice(Message message){
        return messageMapper.insertMessage(message);
    }

    public int readMessage(List<Integer> ids){
        return messageMapper.updateMessagesReadStatus(ids,1);
    }
}
